package org.zjx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.v3.oas.annotations.media.Schema;
import org.zjx.common.util.BeanUtil;
import org.zjx.dao.dto.AccountDTO;
import org.zjx.dao.entity.Account;
import org.zjx.dao.mapper.AccountMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.zjx.dao.vo.AccountVO;
import org.zjx.service.IAccountService;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2025-05-28
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {

    @Override
    public AccountVO getAccountVOByAccountId(Long accountId) {
        Account account = this.getById(accountId);

        // 校验用户状态
        if (account == null || account.getStatus() == 0) {
            throw new RuntimeException("用户状态异常！");
        }

        return BeanUtil.copyProperties(account, AccountVO.class);
    }

    @Override
    public AccountVO getAccountVOByAccount(String account) {
        Account account1 =  lambdaQuery()
                .eq(account != null, Account::getAccount, account)
                .one();

        // 校验用户状态
        if (account1 == null || account1.getStatus() == 0) {
            throw new RuntimeException("用户状态异常！");
        }

        return BeanUtil.copyProperties(account1, AccountVO.class);
    }

    @Override
    public String queryGeneral(String phone) {
        Account account =  lambdaQuery()
                .eq(phone != null, Account::getPhone, phone)
                .one();
        return account == null ? null : account.getGeneral();
    }

    @Override
    public boolean updateAccountGeneral(AccountDTO accountDTO) {
        Long id = accountDTO.getId();
        String account = accountDTO.getAccount();
        String phone = accountDTO.getPhone();
        String general = accountDTO.getGeneral();

        if (general == null || general.trim().isEmpty()) {
            return false; // 将军令不能为空
        }

        // 构建动态查询条件
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
        if (id != null && id != 0) wrapper.eq(Account::getId, id);
        if (!account.isEmpty()) wrapper.eq(Account::getAccount, account);
        if (phone != null) wrapper.eq(Account::getPhone, phone);

        // 必须至少有一个查询条件
        if (wrapper.getExpression() == null) {
            throw new IllegalArgumentException("至少需要提供一个查询条件");
        }

        Account account1 =  this.getOne(wrapper);
        if (account1 == null || account1.getStatus() == 0) {
            return false; // 用户不存在或状态异常
        }

        account1.setGeneral(general);
        return this.updateById(account1);
    }
}
